var express = require('express');
const { success, fail } = require('../utils/response');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
  success(res, {},
    "操作成功"
  )
});

// 1. 配置存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = 'uploads/';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir);
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1E9)}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  }
});

// 2. 文件过滤
const fileFilter = (req, file, cb) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
  if (!allowedTypes.includes(file.mimetype)) {
    return cb(new Error('仅支持 JPG/PNG/PDF 文件'), false);
  }
  cb(null, true);
};

// 3. 初始化上传中间件
const upload = multer({
  storage,
  limits: {
    fileSize: 10 * 1024 * 1024 // 10MB限制
  },
  fileFilter
});


router.post('/upload', upload.single('file'), function (req, res) {
  if (!req.file) {
    return fail(res, "未选择文件");
  }
  success(res, {
    originalName: req.file.originalname,
    fileName: req.file.filename,
    path: `/uploads/${req.file.filename}`,
    size: req.file.size
  }, "上传成功")
})


module.exports = router;
